<template>
  <div class="base-list page-component__scroll el-scrollbar">
    <el-card class="box-card" shadow="hover" :body-style="{padding: 0}">
      <div slot="header" class="clearfix filter-container">
        <list-search
          id="search-header"
          :columns="columns"
          :options="options"
          :permission="permission"
          @filterFetchData="filterFetchData"
          @handleAdd="handleAdd">
          <template slot="button_actions">
            <el-popconfirm
              class="filter-button"
              title="是否批量删除？"
              icon="el-icon-delete"
              icon-color="red"
              style="margin-right: 10px;"
              confirm-button-type="danger"
              @confirm="deleteAll()">
              <el-button slot="reference" v-waves type="danger" icon="el-icon-delete" style="margin-left: 10px">批量删除</el-button>
            </el-popconfirm>
            <slot name="header_actions" :columns="columns" :options="options" :permission="permission"/>
          </template>
        </list-search>

      </div>
      <!--    表格-->
      <list-table
        ref="dataTable"
        :tree-table="treeTable"
        :url="url"
        :show-select="showSelect"
        :show-actions="showActions"
        :id-column="idColumn"
        :columns="columns"
        :list-query="listQuery"
        :options="options"
        :format="format"
        @selectChange="handleSelectionChange"
      >
        <template slot="table_raw_actions" slot-scope="scope">
          <el-popover placement="right">
            <template>
              <el-button v-if="treeTable" v-waves type="primary" plain @click="handleAdd(scope.$index, scope.row)">
                新建子类
              </el-button>
              <el-button v-waves type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-popconfirm
                title="是否删除这条数据？"
                icon="el-icon-info"
                icon-color="red"
                confirm-button-type="danger"
                @confirm="handleDelete(scope.$index, scope.row)">
                <el-button slot="reference" v-waves type="danger" style="margin-left: 10px">删除</el-button>
              </el-popconfirm>
              <slot name="raw_actions" :row="scope.row"/>
            </template>
            <i slot="reference" class="el-icon-more"/>
          </el-popover>
        </template>
      </list-table>
    </el-card>
    <!--编辑器-->
    <el-drawer
      :title="drawerOptions[drawerStatus].title"
      :visible.sync="drawerVisible"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      :wrapper-closable="wrapperClosable"
      direction="rtl"
      :before-close="handleBeforeCloseDrawer"
      :size="$store.state.app.device !== 'mobile' ? editPageWidth : '100%'"
    >
      <slot v-if="editPage" name="raw_edit" :row="temp"/>
      <list-row-edit
        v-else
        :temp="temp"
        :temp-index="tempIndex"
        :url="url"
        :permission="permission"
        :columns="columns"
        :drawer-status="drawerStatus"
        :tree-table="treeTable"
        :rules="rules"
        :options="options"
        :parent-options="parentOptions"
        :id-column="idColumn"
        :transform-fun="transformFun"
        @fetchData="fetchData"
        @handleGetParentOptions="handleGetParentOptions"
        @saveSuccess="saveSuccess"
      />
    </el-drawer>

    <el-backtop target=".page-component__scroll .el-scrollbar__wrap" :bottom="100"/>
  </div>
</template>

<script>
import {getBaseOptions, deleteBase, requestBase, getBaseDetail} from '@/api/common'
import permission from '@/directive/permission' // 权限判断指令
import waves from '@/directive/waves' // waves directive

import ListTable from '@/components/BaseList/components/ListTable'
import ListSearch from '@/components/BaseList/components/ListSearch'
import ListRowEdit from '@/components/BaseList/components/ListRowEdit'
import {deepClone} from '@/utils'
export default {
  name: 'BaseList',
  components: {
    ListTable,
    ListSearch,
    ListRowEdit
  },
  directives: {permission, waves},
  props: {
    idColumn: {type: String, default: 'id'},
    editPage: {type: Boolean, default: false},
    editFunction: {type: Boolean, default: false},
    editPageWidth: {type: String, default: '60%'},
    url: {type: String, default: ''},
    permission: {type: String, default: ''},
    columns: {type: Array, default: () => []},
    rules: {
      type: Object, default: () => {
      }
    },
    options: {
      type: Object, default: () => {
      }
    },
    transformFun: {
      type: Function, default: null
    },
    format: {
      type: Object, default: () => {}
    },
    showSelect: {type: Boolean, default: true},
    showActions: {type: Boolean, default: true},
    defaultExpandAll: {type: Boolean, default: false},
    treeTable: {type: Boolean, default: false},
    initTemp: {type: Object, default: () => { return { 'nothing': 0 } } }
  },
  data: () => {
    return {
      tableLoading: true,
      drawerLoading: false,
      wrapperClosable: false,
      limitQuery: {page: 1, size: 20, asc: undefined, desc: undefined},
      total: 0,
      listQuery: [],
      temp: {},
      tempIndex: -1,
      dialogVisibleImg: false,
      dialogVisibleVideo: false,

      statusOptions: [{id: true, name: '启用'}, {id: false, name: '禁用'}],
      fileUrl: '',
      drawerVisible: false,
      drawerStatus: 0,
      drawerOptions: [
        {value: '', title: ''},
        {value: 'detail', title: '详情'},
        {value: 'edit', title: '编辑'},
        {value: 'add', title: '新建'}
      ],
      parentOptions: [],
      addOrEditLoading: false,
      multipleSelection: [],
    }
  },
  watch: {
    temp: {
      deep: true,
      handler(newVal, oldVal) {
        this.wrapperClosable = false
      }
    }
  },
  created() {
    const query = localStorage.getItem('query_' + this.url)
    if (query) {
      this.limitQuery = JSON.parse(query)
      const shows = this.limitQuery.show.split(',')
      this.columns.forEach(e => {
        e.show = shows.indexOf(e.key) > -1
      })
    }

    this.handleGetParentOptions()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.$emit('selectChange', val)
    },
    deleteAll() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$notify.error('请选择数据!')
        return
      }
      requestBase({url: this.url + '/multi', method: 'DELETE', data: this.multipleSelection.map(e => e.id)}).then(res => {
        this.$notify.success('删除成功!')
        this.$refs.dataTable.fetchData()
        this.multipleSelection = []
        this.$emit('selectChange', [])
      })
    },
    filterFetchData(page, size, listQuery) {
      this.listQuery = listQuery
      this.fetchData(page, size, listQuery)
    },
    fetchData(page, size) {
      this.$nextTick(_ => {
        this.$refs.dataTable.fetchData(page, size)
      })
    },
    handleEdit(index, row) {
      const self = this
      self.temp = {}
      self.tempIndex = index
      getBaseDetail(self.url, row[this.idColumn]).then(res => {
        self.temp = Object.assign(res.data)
        if (this.editFunction) {
          this.$emit('editData', index, self.temp)
        } else if (this.editPage) {
          self.drawerLoading = true
          self.drawerStatus = 2
          self.drawerVisible = true
        } else {
          self.drawerLoading = true
          self.drawerStatus = 2
          self.drawerVisible = true
          self.drawerLoading = false
          self.wrapperClosable = true
        }
      }).catch(() => {
        self.drawerLoading = false
      })
    },
    restTemp(parentId) {
      console.log('0===========', this.initTemp)

      const temp = deepClone(this.initTemp)
      console.log('2===========', temp)
      this.columns.forEach(e => {
        if (!temp[e.key]) {
          let value
          if (e.type === 'MULTI_SELECT' || e.type === 'TREE_MULTI_SELECT') {
            value = []
          }
          if (e.type === 'ENABLE') {
            value = true
          }
          temp[e.key] = value
        }
      })
      const routerQuery = this.$route.query
      for (const key in routerQuery) {
        if (!temp[key]) {
          temp[key] = routerQuery[key]
        }
      }
      this.treeTable && (temp.parentId = parentId)
      this.temp = temp
      console.log('1===========', this.temp)
    },
    handleAdd(index = 0, row = {id: undefined}) {
      const self = this
      self.tempIndex = -1
      if (self.editFunction) {
        self.$emit('editData', -1, row)
      } else if (this.editPage) {
        self.editPageUrl = '#' + self.$route.path + '/edit'
        self.drawerLoading = true
        self.drawerStatus = 2
        self.drawerVisible = true
      } else {
        self.restTemp(row[self.idColumn])
        self.$nextTick(() => {
          self.wrapperClosable = true
        })
        self.drawerStatus = 3
        self.drawerVisible = true
      }
    },
    saveSuccess(index, row) {
      this.drawerVisible = false
      this.$refs.dataTable.setRowData(index, row)
    },
    handleDelete(index, row) {
      const self = this
      deleteBase(self.url, row[this.idColumn]).then(() => {
        self.$notify.success('删除成功!')
        self.fetchData()
        self.handleGetParentOptions()
      })
    },
    handleBeforeCloseDrawer(done) {
      if (!this.wrapperClosable) {
        this.$confirm('您输入的内容将会丢失，是否关闭?', '提示', {
          confirmButtonText: '关闭',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          done(true)
        })
      } else {
        done(true)
      }
    },
    handleTreeNodeClick(val, check) {
      this.temp.permissions = check.checkedNodes
    },
    handleGetParentOptions() {
      this.treeTable && getBaseOptions(this.url, {}).then(res => {
        this.parentOptions = res.data
      })
    },
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-card__header {
  background-color: #f8f8f8;
  padding: 3px !important;
}

.el-tag {
  margin: 0 5px 0 0;
}

.base-list {
  .base-table {
    img {
      height: 30px;
      display: inline;
      vertical-align: middle;
    }
  }

}

</style>
